<?php
namespace common\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $mobile;
    public $smsCode;
    public $captcha;
    public $loginMode;
    public $rememberMe = true;

    private $_user = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required','on' => ['default','login_account']],
            // rememberMe must be a boolean value
            //['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword','on' => ['default','login_account']],
            ['captcha', 'captcha','on' => ['default','login_account']],

            ['mobile', 'required','on' => ['default','login_sms_code']],
            ['mobile', 'integer','on' => ['login_sms_code']],
            ['mobile','match','pattern'=>'/^1[0-9]{10}$/','on' => ['default','login_sms_code'],'message'=>'{attribute}必须为1开头的11位纯数字'],
            ['mobile', 'string', 'min'=>11,'max' => 11,'on' => ['default','login_sms_code']],

            ['smsCode', 'required','on' => ['default','login_sms_code']],
            ['smsCode', 'integer','on' => ['default','login_sms_code']],
            ['smsCode', 'string', 'min'=>6,'max' => 6,'on' => ['default','login_sms_code']],
            ['smsCode', 'required','requiredValue'=>$this->getSmsCode(),'on' => ['default','login_sms_code'],'message'=>'手机验证码输入错误'],
        ];
    }

    public function scenarios()
    {
        return [
            'default' => ['username', 'password', 'captcha','mobile', 'smsCode'],
            'login_account' => ['username', 'password'],
            'login_sms_code' => ['mobile', 'smsCode'],
        ];
    }



    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => Yii::t('app', 'Username'),
            'password' => Yii::t('app', 'Password'),
            'mobile' => Yii::t('app', 'Mobile'),
            'rememberMe' => Yii::t('app', 'Remember Me'),
            'smsCode' => Yii::t('app', 'SMS Code'),
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, Yii::t('app', 'Incorrect username or password.'));
            }
        }
    }



    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 7 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            if (strpos($this->username, "@")){
                $this->_user = User::findByEmail($this->username); //email登录
            }
            elseif(preg_match("/^1[0-9]{10}$/",$this->username)){
                $this->_user = User::findByMobile($this->username); //手机登录
            }
            else{
                $this->_user = User::findByUsername($this->username); //用户名登录
                //$this->_user = User::findByMobile($this->username);
            }

        }

        return $this->_user;
    }

    public function sms_login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUserByMobile(), $this->rememberMe ? 3600 * 24 * 7 : 0);
        } else {
            return false;
        }
    }

    public function getUserByMobile()
    {
        if ($this->_user === false) {
            if(preg_match("/^1[0-9]{10}$/",$this->mobile)){
                $this->_user = User::findByMobile($this->mobile);
            }

        }
        return $this->_user;
    }

    public function getSmsCode(){
        //检查session是否打开

        if(!Yii::$app->session->isActive){
            Yii::$app->session->open();
        }
        //取得验证码和短信发送时间session
        $login_sms_code = intval(Yii::$app->session->get('login_sms_code'));
        $login_sms_time = Yii::$app->session->get('login_sms_time');
        if(time()-$login_sms_time <= 600){
            return $login_sms_time;
        }
        else{
            return 888888;
        }
    }

}
